package com.fuyu.web.kaogong.controller;


import cn.hutool.core.util.ObjUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fuyu.common.model.R;
import com.fuyu.common.model.TokenUserInfo;
import com.fuyu.common.utils.JwtUtil;
import com.fuyu.model.entity.WxUser;
import com.fuyu.system.anno.IgnoreWebSecurity;
import com.fuyu.web.kaogong.models.form.WxLoginForm;
import com.fuyu.web.kaogong.models.params.WxLoginServiceParams;
import com.fuyu.web.kaogong.service.WxUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/wx")
public class WxUserLoginController {

    @Autowired
    private WxUserService wxUserService;

    @IgnoreWebSecurity
    @PostMapping("/login")
    public R<Object> login(@RequestBody WxLoginForm form) {

        WxLoginServiceParams wxLoginServiceParams = new WxLoginServiceParams();
        wxLoginServiceParams.setJs_code(form.getCode());

        log.info(String.valueOf(wxLoginServiceParams));

        String s = HttpUtil.get(
                " https://api.weixin.qq.com/sns/jscode2session",
                JSON.parseObject(JSON.toJSONString(wxLoginServiceParams), Map.class)
        );

        Map res = JSON.parseObject(s, Map.class);

        String openid = (String) res.get("openid");


        if (ObjUtil.isNotNull(res.get("errcode"))) {
            return R.failed("Error");
        }

        WxUser entity = WxLoginForm.toEntity(form);
        entity.setOpenid(openid);


        WxUser wxUserServiceOne = wxUserService.getOne(
                new LambdaQueryWrapper<WxUser>().eq(WxUser::getOpenid, openid)
        );

        if (wxUserServiceOne != null) {
            String token = JwtUtil.createToken(TokenUserInfo.builder()
                    .userId(wxUserServiceOne.getId() + "")
                    .username(openid)
                    .build());
            log.info("当前用户已存在");
            return R.success(token);
        }

        boolean save = wxUserService.save(entity);
        if (!save) {
            return R.failed("用户注册失败");
        }
        String token = JwtUtil.createToken(TokenUserInfo.builder()
                .userId(entity.getId() + "")
                .username(openid)
                .build());
        log.info("用户注册成功");
        return R.success(token);
    }
}
